﻿namespace Whut.ObjectSharePointMapper.Internals
{
    using System;
    using Microsoft.SharePoint;

    public class UpdateAction : SharePointAction
    {
        public UpdateAction(MetaDataStore metaDataStore, SessionLevelCache sessionLevelCache, EntityHydrater entityHydrater)
            : base(metaDataStore, sessionLevelCache, entityHydrater)
        {
        }

        public void Update<TEntity>(TEntity entity)
        {
            ListInfo listInfo = this.MetaDataStore.GetListInfoFor<TEntity>();
            int id = (int)listInfo.Id.PropertyInfo.GetValue(entity, null);
            SPListItem item = this.SessionLevelCache.TryFindSPListItem<TEntity>(id);
            if (item == null)
            {
                throw new ArgumentException("Entity not from this session.", "entity");
            }

            this.EntityHydrater.UnHydrate(entity, item);
            item.Update();
            this.EntityHydrater.ReHydrateLookups(entity, item);
        }
    }
}
